#include "StdAfx.h"
#include "config.h"
#include <string>
#include <memory>
#include <fstream>
#include <sstream>


using namespace std;

struct	cfgbackda
{
	cfgback opfn;
	void * opparam;
};

typedef std::tr1::shared_ptr<cfgbackda> cfgbackda_ptr;

class config::configImp
{
	friend class config;

	std::map<wstring,cfgbackda_ptr> m_opmap;
};

config::config(void)
{
	p_imp = new configImp;
}

config::~config(void)
{
	delete p_imp;
}

void config::addconfig( const wchar_t* option,cfgback fn,void * param )
{	 
	cfgbackda_ptr dap(new cfgbackda);
	dap->opfn = fn;
	dap->opparam = param;
	p_imp->m_opmap[option] = dap;
}

void config::doconfig( const wchar_t* filename )
{
	std::wifstream fin;
	fin.open(filename); 
	if(!fin)
	{
		return ;
	}

	std::wstring buff;
	std::wstring optionvalue;
	while(getline(fin,buff))
	{
		if(buff == L"")continue;
		if(buff[0] == L'#')continue;

		std::wstringstream lbuff;
		lbuff<<buff;
		std::wstring field;
		lbuff>>field;

		std::map<wstring,cfgbackda_ptr>::iterator it = p_imp->m_opmap.find(field);
		if(it != p_imp->m_opmap.end())
		{
			cfgbackda * func = it->second.get();
			std::wstring tempstr;
			getline(lbuff,tempstr);
			optionvalue = tempstr.substr(1);
			func->opfn(optionvalue.c_str(),func->opparam);
		}

	}

}
